---
title: sdk/worker
description: The RedwoodSDK worker
next: false
---

The `rwsdk/worker` module exports the `defineApp` function, which is the entry point for your Cloudflare Worker.

This is the shape of a Cloudflare Worker:

```tsx
export default {
  fetch: (request: Request) => {
    return new Response("Hello, World!");
  },
};
```

This is the shape of a RedwoodSDK Worker:

```ts
import { defineApp } from "rwsdk/worker";

const app = defineApp();
export default {
  fetch: app.fetch,
};
```

## `defineApp`

The `defineApp` function is used to manage how Cloudflare Workers should process requests and subsequently return a response.

```ts
import { defineApp } from 'rwsdk/worker'
import { route } from 'rwsdk/router'

defineApp([
  // Middleware
  function  middleware1({ request, ctx }) {
    ctx.var1 = 'we break'
  },
  function  middleware1({ request, ctx }) {
    ctx.var1 = ctx.var1 + ' abstractions'
  },
  // Route handlers
  route('/', ({ ctx }) => new Response(ctx.var1)), // we break abstractions
  route('/ping', () => new Response('pong!')),
]);

---
In this example above a request would be processed by the middleware, then the correct route would match and execute the handler.
---

## `ErrorResponse`

The `ErrorResponse` class is used to return an errors that includes a status code, a message, and a stack trace. You'll be able to extract this information in try-catch blocks, handle it, or return a proper request response.

```ts
import { ErrorResponse } from "rwsdk/worker";

export default defineApp([
  async ({ ctx, request, response }) => {
    try {
      ctx.session = await sessions.load(request);
    } catch (error) {
      if (error instanceof ErrorResponse && error.code === 401) {
        await sessions.remove(request, response.headers);
        response.headers.set("Location", "/user/login");

        return new Response(null, {
          status: 302,
          headers: response.headers,
        });
      }

      throw error;
    }
  },
  route("/", () => new ErrorResponse(404, "Not Found")),
]);
```

## `requestInfo: RequestInfo`

The `requestInfo` object is used to get information about the current request. It's a singleton that's populated for each request, and contains the following information.

- `request`: The incoming HTTP [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object
- `response`: A [ResponseInit](https://fetch.spec.whatwg.org/#responseinit) object used to configure the status and headers of the response
- `ctx`: The app context (same as what's passed to components)
- `rw`: RedwoodSDK-specific context
- `cf`: Cloudflare's Execution Context API